package com.open.cinema.system;

import com.github.pagehelper.PageHelper;
import com.open.cinema.common.model.ApplicationInfo;
import com.open.cinema.system.util.SpringContextUtil;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
//import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
//import org.springframework.cloud.netflix.feign.EnableFeignClients;
//import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@EnableAutoConfiguration
//@EnableEurekaClient
//@EnableFeignClients(basePackages = "com.open.family")
//@EnableHystrix
//@EnableDiscoveryClient
@EnableWebMvc
@SpringBootApplication
@ComponentScan("com.open.cinema")
@MapperScan({"com.open.cinema.*.mapper", "com.open.cinema.*.mapper.*"})
@RestController
public class Application extends WebMvcConfigurerAdapter {
    private static Logger logger = Logger.getLogger(Application.class);

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }


    @Bean
    public ApplicationInfo getApplicationInfo() throws IOException, XmlPullParserException {
        ApplicationInfo applicationInfo = new ApplicationInfo();
        MavenXpp3Reader reader = new MavenXpp3Reader();
        String pomPath = "";
        InputStream inputStream;
        if (ClassLoader.getSystemResource("META-INF/maven/com.r7tech.sandata") != null) {
            inputStream = ClassLoader.getSystemResourceAsStream(
                    "META-INF/maven/com.open.cinema/cinema-system/pom.xml");
        } else {
            inputStream = new FileInputStream(System.getProperty("user.dir") + "/cinema-system/pom.xml");
        }
        Model model = reader.read(inputStream);
        inputStream.close();
        applicationInfo.setApplicationName(model.getArtifactId());
        applicationInfo.setVersion(model.getVersion());
        return applicationInfo;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 添加分页插件
        PageHelper pageHelper = new PageHelper();
        Properties props = new Properties();
        props.setProperty("reasonable", "true");
        props.setProperty("supportMethodsArguments", "true");
        props.setProperty("returnPageInfo", "check");
        props.setProperty("params", "count=countSql");
        props.setProperty("pageSizeZero", "true");
        pageHelper.setProperties(props);
        sqlSessionFactoryBean.setPlugins(new Interceptor[] {pageHelper});

        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean
                .setConfigLocation(resolver.getResource("classpath:mybatis-configuration.xml"));
        sqlSessionFactoryBean
                .setMapperLocations(resolver.getResources("classpath*:/mybatis/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }


    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS",
                        "TRACE");
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        ApplicationContext applicationContext = app.run(args);
        SpringContextUtil.setApplicationContext(applicationContext);
        logger.info("SpringBoot Start Success");
    }

}
